package com.tomvian.tools 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.system.System;
	import flash.utils.getTimer;
	
	/**
	 * StatsGraphDisplay
	 * @author Tom Vian
	 */
	public class StatsGraphDisplay extends Bitmap 
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		private var _bmd:BitmapData;
		
		private var _overFramerate:Number;
		
		private var _timer : uint;
		private var _timerPrev : uint;
		
		private var _frames : uint;
		
		private var _maxMemory:Number;
		
		private var _clearRect:Rectangle;
		
		private var _barRect:Rectangle;
		
		private var _copyPoint:Point;
		
		//--------------------------------------------------------------------------
		//
		//  Getters / Setters
		//
		//--------------------------------------------------------------------------
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function StatsGraphDisplay(maxMemory:Number = -1) 
		{
			super(_bmd = new BitmapData(200, 200, false, 0));
			
			_maxMemory = maxMemory;
			
			_clearRect = new Rectangle(199, 0, 1, 200);
			
			_barRect = new Rectangle(199, 0, 1, 1);
			
			_copyPoint = new Point(-1, 0);
			
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}
		
		private function onAdded(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			
			_overFramerate = 1.0 / stage.frameRate;
			
			OmniTick.tick.onTick.add(update);
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		private function update():void 
		{
			_timer = getTimer();
			
			if( _timer - 200 > _timerPrev )
			{
				var overTimerDiff:Number = 1.0 / Number(_timer - _timerPrev);
				
				// FPS as a fraction of target FPS
				var fps:Number = _frames * _overFramerate * overTimerDiff * 1000.0;
				
				// Memory in MB
				var mem:uint = System.privateMemory / 1048576;
				
				_bmd.copyPixels(_bmd, _bmd.rect, _copyPoint);
				
				_bmd.fillRect(_clearRect, 0);
				
				_barRect.height = 200 * mem / _maxMemory;
				_barRect.y = 200 - _barRect.height;
				
				_bmd.fillRect(_barRect, 0x4A6FC1);
				
				_bmd.setPixel(199, int(200 - (fps * 150)), 0xEC2B20);
				
				_frames = 0; 
				_timerPrev = _timer;
			}
			
			_frames++;
		}
	}
}